<?php
namespace Zxf5115\Laravel\Advertising\Models\Common;

use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Zxf5115\Laravel\Kernel\Models\Base;

/**
 * @author zhangxiaofei [<1326336909@qq.com>]
 * @dateTime 2025-09-22
 *
 * 广告模型类
 */
class Advertising extends Base
{
  /**
   * 数据库连接名
   */
  protected $connection = 'business';

  /**
   * 数据库表名
   */
  protected $table = "module_advertising";

  /**
   * 批量赋值允许的字段
   */
  protected $fillable = [
    'id',
  ];

  /**
   * 需要隐藏的字段
   */
  protected $hidden = [
    'update_time'
  ];


  /**
   * 筛选指定广告位的广告作用域
   *
   * @param Builder $query
   * @param int $position_id
   * @return Builder
   */
  public function scopeWherePosition(Builder $query, int $position_id) : Builder
  {
    return $query->where(['position_id' => $position_id, 'status' => 1]);
  }


  // 关联函数 ------------------------------------------------------

  /**
   * 广告与广告位的关联
   *
   * @return [关联对象]
   */
  public function position() : BelongsTo
  {
    return $this->belongsTo(
      'Zxf5115\Laravel\Advertising\Models\Common\Advertising\Position',
      'position_id',
      'id'
    )->select(['id', 'name'])->where(['status'=>1]);
  }


  /**
   * 广告与广告详情的关联
   *
   * @return [关联对象]
   */
  public function detail() : HasOne
  {
    return $this->hasOne(
      'Zxf5115\Laravel\Advertising\Models\Common\Advertising\Detail',
      'advertising_id',
      'id'
    );
  }


  /**
   * 执行事件回调
   */
  protected static function boot() : void
  {
    parent::boot();

    // 删除广告时同时删除关联的详情
    static::deleted(function(self $model) : void {
      $model->detail()->delete();
    });
  }
}
